package com.chub.study.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

/**
 * @author : chub
 * @version : V1.0.0
 * @fileName : CustomDateJsonSerializer.java
 * @description : 日期反序列化工具,直接将时间类型的转为yyyy-MM-dd类型的数据
 * @createTime : 2021-10-27 14:12
 */
public class CustomDateJsonDeserializer extends JsonDeserializer<LocalDateTime> {

    //定义日期格式
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter fmt2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        System.out.println("this is a test !");
        String jsonStr = p.getText();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(jsonStr, dateTimeFormatter);
        return localDate.atStartOfDay();

//        if (jsonStr.matches("\\d{4}[-]\\d{2}[-]\\d{2}")) {
//            DateUtil.parse
//            return DateUtil.parseLocalDateTime(jsonStr);
//        }
//        try {
//            if (p != null) {
//                return LocalDateTime.parse(p.getText(), fmt1);
////                return format.parse(p.getText());
//            } else {
//                return null;
//            }
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            throw new RuntimeException(e);
//        }
//        return null;
    }
}
